package com.geekhole.demo.v4.application;

import com.geekhole.demo.application.UserApplication;
import com.geekhole.demo.domain.CreateAndEnableUserContext;
import com.geekhole.demo.domain.ModifyUserNameContext;
import com.geekhole.demo.domain.User;
import com.geekhole.demo.domain.UserNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

@Service
public class UserV4Application
    extends BaseV4Application
    implements UserApplication {
    @Autowired
    private JpaRepository<User, Long> repository;

    @Override
    public void createAndEnableUser(CreateAndEnableUserContext context) {
        this.<User, CreateAndEnableUserContext>creatorFor(this.repository)
                .instance(createAndEnableUserContext -> User.create(createAndEnableUserContext.getName(), createAndEnableUserContext.getAge()))
                .update((user, createAndEnableUserContext) -> user.enable())
                .call(context);
    }

    @Override
    public void modifyUserName(ModifyUserNameContext context) {
        this.<User, ModifyUserNameContext>updaterFor(repository)
                .loader(domainServiceContext -> this.repository.getById(domainServiceContext.getUserId()))
                .onNotFound(modifyUserNameContext -> {throw new UserNotFoundException(modifyUserNameContext.getUserId());})
                .update((user, modifyUserNameContext) -> user.modifyUserName(modifyUserNameContext.getNewName()))
                .call(context);
    }
}
